<template>
  <el-row class="RangeDrawer">
    <commonDrawer
      :title="drawerType === 'add' ? '新增字段' : '编辑字段'"
      :drawer="drawer"
      :size="600"
      :isShowMoreBtn="true"
      @closeDraw="closeDraw"
      @cancelFun="closeDraw"
      @save="save"
    >
      <template slot="column">
        <div class="range-area" v-loading="loading">
          <el-form
            ref="formRef"
            :model="form"
            class="m7-form"
            label-position="top"
            :rules="rules"
          >
            <el-form-item label="字段类型" prop="type">
              <el-select
                v-model="form.type"
                filterable
                placeholder="请选择字段类型"
                style="width: 100%"
                :disabled="drawerType === 'add' ? false : true"
                @change="TypeChange"
              >
                <el-option
                  v-for="item in typeArr"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字段名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入字段名称"
                :maxlength="50"
                clearable
                :disabled="form.category === 'system'"
                @change="changeFieldName"
              ></el-input>
            </el-form-item>
            <el-form-item
              v-show="form.category === 'system'"
              label="自定义名称"
              prop="alias"
            >
              <el-input
                v-model="form.alias"
                placeholder="请输入自定义名称"
                :maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="字段参数" prop="param">
              <el-input
                v-model="form.param"
                placeholder="请输入字段参数"
                :maxlength="20"
                clearable
                :disabled="form.category === 'system'"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="['cascade'].includes(form.type)">
              <span slot="label"
                ><span style="color: #f56c6c; margin-right: 4px">*</span
                >层级</span
              >
              <el-select
                v-model="form.level"
                filterable
                :disabled="onlyShow"
                placeholder="请选择层级"
                style="width: 100%"
                @change="setLevel"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="item in [1, 2, 3, 4, 5]"
                  :key="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="
                ['dropdown', 'checkbox', 'cascade', 'radio'].includes(
                  form.type
                ) && showOption
              "
            >
              <span slot="label"
                ><span style="color: #f56c6c; margin-right: 4px">*</span
                >选项</span
              >
              <Select
                ref="Select"
                v-if="['dropdown', 'radio'].includes(form.type)"
                @hook:updated="previewChange"
              ></Select>
              <Checkbox
                ref="Checkbox"
                v-if="form.type === 'checkbox'"
                @hook:updated="previewChange"
              ></Checkbox>
              <Cascader
                ref="Cascader"
                v-if="form.type === 'cascade'"
                @hook:updated="previewChange"
              ></Cascader>
            </el-form-item>
            <el-form-item>
              <span slot="label">字段规则</span>
              <el-checkbox-group v-model="form.fieldRule">
                <el-checkbox label="searchable">可查询</el-checkbox>
                <el-checkbox
                  label="oplog"
                  :disabled="form.category === 'system'"
                  >操作日志</el-checkbox
                >
              </el-checkbox-group>
              <!-- <div style="font-size:12px" v-if="['date', 'datetime'].includes(form.type)">可以选未来
                <el-input-number style="width:80px;margin:0px 5px" v-model="form.f5"
                  :controls="false" :min="0" :max="6" :step="1" size="small">
                </el-input-number>
                个月
                <div style="color: #B3B9C7">最多6个月，不填不可选未来时间</div>
              </div> -->
            </el-form-item>
            <el-form-item v-if="['cascade'].includes(form.type)">
              <span slot="label">层级必选</span>
              <el-checkbox
                v-model="form.fillLevel"
                @change="previewChange"
                :disabled="onlyShow"
                >必选全部层级</el-checkbox
              >
              <el-tooltip
                content="必选全部层级指当该字段为必填项时候，级联菜单的所有层级都必选，否则不能保存，非必选全部层级指选至任意一级即可"
                placement="top"
              >
                <i
                  style="
                    font-size: 12px;
                    color: #b3b9c7;
                    margin-left: 6px;
                    cursor: pointer;
                  "
                  class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
                ></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="效果预览">
              <Preview ref="Preview"></Preview>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </commonDrawer>
  </el-row>
</template>

<script lang="ts">
/**
 * 客户字段编辑
 */
import { Component, Vue, Ref } from 'vue-property-decorator';
import commonDrawer from '@/components/globalTool/resizeDrawer/drawer.vue';
import { commonAction, deepClone } from '@/utils/common';
import Select from './components/select.vue'
import Checkbox from './components/checkbox.vue'
import Cascader from './components/cascader.vue'
import Preview from './components/preview.vue'
import { typeArr } from './components/typeMap'
import { CommonModule } from '@/store/modules/common'
const defaultData = {
  type: '',
  name: '',
  param: '',
  alias: '',
  fieldRule: [],
  fillLevel: false,
  level: 2
}
@Component({
  name: 'EditFields',
  components: {
    commonDrawer,
    Select,
    Checkbox,
    Cascader,
    Preview
  }
})
export default class EditFields extends Vue {
  [x: string]: any
  @Ref() private readonly Cascader: any
  @Ref() private readonly Select: any
  @Ref() private readonly Checkbox: any
  @Ref() private readonly Preview: any
  private drawer: boolean = false
  private drawerType: string = 'add'
  private data: any
  private loading: boolean = false
  // 字段类型数组
  private typeArr = typeArr().slice(0, 11)
  private form: any = {}
  private showOption: boolean = true // 系统预置的下拉、复选、单选、级联没预置数据不显示选项
  private onlyShow: boolean = false // 系统预置的下拉、复选、单选、级联有预置数据不可编辑

  get getCusInputCon () { // 获取录入面板配置
    const inputConfs = (CommonModule as any).publicCache.customerInputConfig || []
    return inputConfs
  }

  get getCusDetailCon () { // 获取详情面板配置
    const detailConfs = (CommonModule as any).publicCache.customerDetailConfig || []
    return detailConfs
  }

  // 根据输入框类型返回不同的预览数据
  private getOptionsData (type) {
    switch (type) {
      case 'dropdown':
        return this.Select.getData()
      case 'radio':
        return this.Select.getData()
      case 'checkbox':
        return this.Checkbox.getData()
      case 'cascade':
        return { ...this.Cascader.getData(), fillLevel: this.form.fillLevel ? this.form.level : 0 }
      case 'number':
        return {
          value: undefined
        }
      default:
        return {}
    }
  }

  // 监听组件的update，渲染预览数据
  private previewChange () {
    this.$nextTick(() => {
      let data = {
        type: this.form.type,
        field: this.form.name,
        value: '',
        data: []
      }
      data = { ...data, data: this.showOption && this.getOptionsData(this.form.type) }
      this.Preview.setData(data)
    })
  }

  private changeFieldName () {
    this.previewChange()
  }

  private TypeChange (type) {
    this.$nextTick(() => {
      switch (type) {
        case 'dropdown':
          this.Select.setData([], [])
          break
        case 'radio':
          this.Select.setData([], [])
          break
        case 'checkbox':
          this.Checkbox.setData([])
          break
        case 'cascade':
          this.Cascader.setData([], this.form.level)
          break
      }
      this.previewChange()
    })
  }

  private rules = {
    type: [{ required: true, trigger: 'blur', message: '请选择字段类型' }],
    name: [{ required: true, trigger: 'blur', message: '请输入字段名称' }]
  }

  private getSex (val: any) {
    switch (val) {
      case 'N':
        return '保密'
      case 'F':
        return '女'
      case 'M':
        return '男'
    }
  }

  private async openDraw (data: any = defaultData, type: string) {
    this.drawer = true
    this.drawerType = type
    if (data.field === 'gender') {
      data.choices.map(item => {
        item.value = this.getSex(item.key)
      })
    }
    this.form = deepClone({ ...defaultData, ...data })
    const { oplog, searchable, options, choices } = this.form
    this.form.fieldRule = [oplog && 'oplog', searchable && 'searchable']
    if (data.category === 'system' && !data.choices && !data.options) { // 系统预置字段无选项的隐藏选项部分
      this.showOption = false
      this.previewChange()
      return
    } else if (data.category === 'system' && data.field !== 'source' && (data.choices || data.options)) {
      this.showOption = true
      this.onlyShow = true
    } else {
      this.showOption = true
      this.onlyShow = false
    }
    this.$nextTick(() => {
      if (['dropdown', 'radio'].includes(this.form.type)) { // 下拉回显
        this.Select.setData(choices || [], choices && choices.filter(item => item.isDefault), this.onlyShow)
      } else if (this.form.type === 'checkbox') { // 复选框
        this.Checkbox.setData(choices, this.onlyShow)
      }
      if (this.form.type === 'cascade') { // 级联回显
        this.form.fillLevel = Boolean(options && options.fillLevel)
        this.form.level = options && options.level
        this.Cascader.setData(options && options.children, this.form.level, this.onlyShow)
      }
    })
    this.previewChange()
  }

  private closeDraw () {
    this.drawer = false;
  }

  // 设置级联层级
  private setLevel () {
    this.Cascader.setLevel(this.form.level)
  }

  private save () {
    (this as any).$refs.formRef.validate(async (valid) => {
      if (valid) {
        const { type, name, param, fieldRule, field, level, alias, fillLevel } = this.form
        const sendData: any = {
          type,
          name,
          param,
          alias,
          fillLevel,
          searchable: fieldRule.some(item => item === 'searchable'),
          oplog: fieldRule.some(item => item === 'oplog')
        }
        // 校验选项有没有填
        if (['dropdown', 'checkbox', 'radio'].includes(type)) {
          sendData.choices = this.getOptionsData(type)
          if (sendData.choices && !sendData.choices.length) {
            return this.$message.error('请填写选项')
          }
        } else if (['cascade'].includes(type)) {
          const options = this.getOptionsData(type)
          if (options.children && !options.children.length) {
            return this.$message.error('请填写选项')
          } else {
            sendData.options = options
          }
        }
        const actionData = {
          url: this.drawerType === 'add' ? '/server-crm/action/config/customer/field/create' : '/server-crm/action/config/customer/field/update',
          method: 'POST',
          data: this.drawerType === 'add' ? sendData : { ...sendData, field }
        }
        const res = await commonAction(actionData)
        if (res.success) {
          this.drawer = false
          this.$emit('updateData')
          this.$message.success(`${this.drawerType === 'add' ? '创建' : '修改'}成功`)
          if (this.drawerType === 'edit') { // 更新缓存中的内容
            ['getCusInputCon', 'getCusDetailCon'].forEach(v => { // 录入面板、详情面板
              this[v].forEach(item => {
                if (item.field === res.data.field) {
                  item.name = res.data.alias ? res.data.alias : res.data.name
                  if (res.data && res.data.choices) {
                    item.choices = res.data.choices
                  }
                  if (res.data && res.data.options) {
                    item.options = res.data.options
                  }
                }
              })
            })
            this.$updateCache('customerAllFields', res.data, 'field', false)
          } else {
            this.$addOneCache('customerAllFields', res.data, false)
          }
        }
      }
    })
  }
}
</script>

<style lang="stylus" scoped>
.RangeDrawer
  .range-area
    .rightButton
      position absolute
      top 0px
      right 0px
      padding-top 0px
      height 12px
</style>
